package com.hibernate.learn2;

import com.hibernate.learn2.models.Passport;
import com.hibernate.learn2.models.Person;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

public class Main {
    public static void main(String[] args) {

        Configuration configuration = new Configuration().configure("1hibernate.cfg.xml");
        configuration.addAnnotatedClass(Person.class);
        configuration.addAnnotatedClass(Passport.class);

        StandardServiceRegistry ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        SessionFactory sessionFactory = configuration.buildSessionFactory(ssrb);


        newPerson(sessionFactory, "Aleksandr", 5345);

        Person person = getPerson(sessionFactory, 1);

        System.out.printf("name: %s, passport id: %d\n", person.getName(), person.getPassport().getSerial());

        /*
        boolean statusDelete = deletePerson(sessionFactory, 1);
        System.out.printf("status delete is %b\n", statusDelete);
         */

        sessionFactory.close();

    }

    public static void newPerson(SessionFactory sessionFactory, String personName, int serial) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();

        Passport passport = new Passport();
        passport.setSerial(serial);

        Person person = new Person();
        person.setName(personName);
        person.setPassport(passport);

        passport.setOwner(person);

        session.save(person);

        session.getTransaction().commit();
        session.close();

    }

    public static Person getPerson(SessionFactory sessionFactory, int user_id) {

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        Person person = session.find(Person.class, user_id);

        session.getTransaction().commit();
        session.close();

        return person;

    }

    public static boolean deletePerson(SessionFactory sessionFactory, int user_id) {

        Session session = sessionFactory.openSession();
        session.beginTransaction();

        Person person = session.find(Person.class, user_id);
        if (person != null) {
            session.delete(person);

            session.getTransaction().commit();
            session.close();

            return true;
        }

        session.close();
        return false;

    }
}
